<?php
	function checkBattle()
	{
		$cid = $_SESSION['cid'];
		$time = time();
		$q = mysql_query("SELECT * FROM battle_log WHERE player1cid='$cid' AND endtime <= '$time' AND winner='0' OR player2cid ='$cid' AND endtime <= '$time' AND winner='0'");
		if(mysql_num_rows($q) == 1)
		{
			alert("You are in the middle of a fight.");
			redirect("?page=battle");
		}
	}

	$cid = $_SESSION['cid'];
	$time = time();
	$q = mysql_query("SELECT * FROM battle_log WHERE player1cid='$cid' AND endtime <= '$time' AND winner='0' OR player2cid ='$cid' AND endtime <= '$time' AND winner='0'");
	if(mysql_num_rows($q) == 1)
	{
		$f = mysql_fetch_array($q);
		if($cid == $f['player1cid'])
		{
			calculateBattle($f['player2cid']);
		}
		else
		{
			calculateBattle($f['player2cid']);
		}
	}

	function setBattle()
	{
		$cid = $_SESSION['cid'];
		$cid2 = $_GET['id'];
		//query player 1 (Attacker)
		$q = mysql_query("SELECT * FROM characters WHERE id = '$cid'");
		$f = mysql_fetch_array($q);

		//query player 2 (defender)
		$q2 = mysql_query("SELECT * FROM characters WHERE id = '$cid2'");
		$f2 = mysql_fetch_array($q2);

		//Player 1 (Attacker) Stats
		$player1strength = getCharTotalAttack($f['id']);
		$player1defence = getCharTotalDefence($f['id']);
		$player1hp = getCharCurrHp($f['aid']);
		$player1energy = getCharCurrEnergy($f['aid']);

		//Player 2 (Defender) Stats
		$player2strength = getCharTotalAttack($f2['id']);
		$player2defence = getCharTotalDefence($f2['id']);
		$player2hp = getCharCurrHp($f2['aid']);
		$player2energy = getCharCurrEnergy($f2['aid']);

		//randomize
		$random1 = rand(1, 5);
		$random1 = 1+($random1/10);

		$random2 = rand(1, 5);
		$random2 = 1+($random2/10);

		$randomsql1 = 100*$random1;
		$randomsql2 = 100*$random2;

		//alert($random1.' - '.$random2);

		//Calculate both damages
		$player1damage = ($player1defence - $player2strength) * $random1;
		$player2damage = ($player2defence - $player1strength) * $random2;


		$energycalc = 2*round($player1damage/100 * 32);
		if($player1energy < $energycalc)
		{
			alert("You don't have enough energy to start a battle.");
			redirect(getUrl());
			$error = 1;
		}

		$hpcalc = $player1damage*1.2;
		if($player1hp < $hpcalc)
		{
			alert("You don't have enough HP to start a battle.");
			redirect(getUrl());
			$error = 1; 	
		}
		
		if($error != 1 || !isset($error))
		{
			//Battle Timer
			$timer = round((($player1damage + $player2damage)/10))*60;
			$endtime = time()+$timer;

			mysql_query("INSERT INTO battle_log (player1cid, player2cid, endtime, random1, random2) VALUES ('$cid', '$cid2', '$endtime', '$randomsql1', '$randomsql2')");
			sendServerMessage(getNameFromCid($cid2), 'Battle.', 'You got attacked by <a href="?page=profile&id='.$cid.'">'.getNameFromCid($cid).'</a>!<br>');
			redirect(getUrl());
		}
		
	}

	function calculateBattle($cid)
	{
		//query player 1 (Attacker)
		$q = mysql_query('SELECT * FROM characters WHERE id = '.$_SESSION['cid'].'');
		$f = mysql_fetch_array($q);

		//query player 2 (defender)
		$q2 = mysql_query('SELECT * FROM characters WHERE id ='.$cid.'');
		$f2 = mysql_fetch_array($q2);

		//query to get info from log
		$q3 = mysql_query("SELECT * FROM battle_log WHERE player1cid = '".$_SESSION['cid']."' AND player2cid = '".$cid."' AND winner='0' OR player1cid = '".$cid."' AND player2cid = '".$_SESSION['cid']."'  AND winner='0'");
		$f3 = mysql_fetch_array($q3);

		$Bid = $f3['id'];
		
		//Player 1 (Attacker) Stats
		$player1strength = getCharTotalAttack($f['id']);
		$player1defence = getCharTotalDefence($f['id']);
		$player1hp = getCharCurrHp($f['aid']);
		$player1energy = getCharCurrEnergy($f['aid']);

		//Player 2 (Defender) Stats
		$player2strength = getCharTotalAttack($f2['id']);
		$player2defence = getCharTotalDefence($f2['id']);
		$player2hp = getCharCurrHp($f2['aid']);
		$player2energy = getCharCurrEnergy($f2['aid']);

		//randomize
		$random1 = $f3['random1']/100;
		$random2 = $f3['random2']/100;

		//alert($random1.' - '.$random2);

		//Calculate both damages
		$player1damage = ($player1defence - $player2strength) * $random1;
		$player2damage = ($player2defence - $player1strength) * $random2;

		//alert('Player1Damage: '.$player1damage.' -  Player2Damage: '.$player2damage.'\n');

		if($player1damage > $player2damage)
		{
			alert('You won a battle against '.getNameFromCid($cid).'!');
			$winner = 1;
			$WinnerCid = $_SESSION['cid'];
			$WinnerExp = $player1damage * $f['level'] * 10;


			$WinnerRestHpcalc = $player2damage*1.2;
			if($player1hp < $WinnerRestHpcalc)
			{
				$WinnerRestHp = 0;
			}
			else
			{
				$WinnerRestHp = $player1hp-$WinnerRestHpcalc;
			}
			
			$energycalc = 2*round($player1damage/100 * 32);
			$WinnerEnergy = $player1energy-$energycalc;

			$LoserCid = $cid;
		}
		else if($player1damage < $player2damage)
		{
			alert('You lost a battle against '.getNameFromCid($cid).'!');
			$winner = 2;
			$WinnerCid = $cid;
			$WinnerExp = ($player2damage * $f2['level'])/3;
			
			$WinnerRestHpcalc = $player1damage*1.2;
			if($player2hp < $WinnerRestHpcalc)
			{
				$WinnerRestHp = 0;
			}
			else
			{
				$WinnerRestHp = $player2hp-$WinnerRestHpcalc;
			}

			$energycalc = 2*round($player2damage/100 * 32);
			$WinnerEnergy = $player2energy-$energycalc;

			$LoserCid = $_SESSION['cid'];
		}
		else
		{
			alert('Your battle against '.getNameFromCid($cid).' resulted into a draw!');
			$winner = 0;
		}

		//Hospital Timer
		$timer = round((($player1damage + $player2damage)/10))*60;
		$hospital = $timer * 2;

		//get xp
		$WinnerCurrXp = getCharCurrXP($WinnerCid);
		$WinnerXP = $WinnerCurrXp+$WinnerExp;

		//Get AID
		$WinnerAid = getAidFromCid($WinnerCid);
		$LoserAid = getAidFromCid($LoserCid);

		//get loser pollar
		$LoserCurrPollar = getPollars($LoserAid);
		$LoserPollar = 0;

				//get winner pollar
		$WinnerCurrPollar = getPollars($WinnerAid);
		$WinnerPollar = $WinnerCurrPollar+$LoserCurrPollar;

		//getKills
		$WinnerCurrKills = getCharKills($WinnerCid);
		$WinnerKills = $WinnerCurrKills+1;

		//getLosses
		$LoserCurrDeaths = getCharDeaths($LoserCid);
		$LoserDeaths = $LoserCurrDeaths+1;

		//alert($WinnerPollar);
		
		//update Winner
		mysql_query("UPDATE characters SET xp='$WinnerXP', hp='$WinnerRestHp', energy='$WinnerEnergy', wins='$WinnerKills' WHERE id='$WinnerCid'")or die(alert(mysql_error()));
		mysql_query("UPDATE account SET pollars='$WinnerPollar' WHERE id='$WinnerAid'")or die(alert(mysql_error()));

		mysql_query("UPDATE characters SET hp='0', losses='$LoserDeaths' WHERE id='$LoserCid'")or die(alert(mysql_error()));
		mysql_query("UPDATE account SET pollars='$LoserPollar' WHERE id='$LoserAid'")or die(alert(mysql_error()));
		
		mysql_querY("UPDATE battle_log SET winner='$WinnerCid' WHERE id='$Bid'")or die(alert(mysql_error()));

		sendServerMessage(getNameFromCid($LoserCid), 'You lost a battle.', 'You got killed by <a href="?page=profile&id='.$WinnerCid.'">'.getNameFromCid($WinnerCid).'</a> and lost all your money.<br>');

		//alert('Player1Damage: '.$player1damage.' -  Player2Damage: '.$player2damage.'\nWinnerExp: '.$WinnerExp.'\nWinnerRestHp: '.$WinnerRestHp.'\nWinnerEnergy: '.$WinnerEnergy);
	}

	function battlesystem()	
	{
		$cid = $_SESSION['cid'];

		//query player 1 (Attacker)
		$q = mysql_query('SELECT * FROM characters WHERE id = '.$_SESSION['cid'].'');
		$f = mysql_fetch_array($q);

		//query player 2 (defender)
		$q2 = mysql_query('SELECT * FROM characters WHERE id ='.$_GET['id'].'');
		$f2 = mysql_fetch_array($q2);

		$q3 = mysql_query("SELECT * FROM battle_log WHERE player1cid='$id' AND endtime > '$time' AND winner='0' OR player2cid ='$id' AND endtime > '$time' AND winner='0'");
		$f3 = mysql_fetch_array($q);
		if(mysql_num_rows($q3) == 1)
		{
			if($cid == $f3['player1cid'])
			{
				if($_GET['id'] != $f3['player2cid'])
				{
					alert("You are already batteling someone.");
					redirect("?page=battle&id=".$f3['player2cid']);
				}
			}
			else
			{
				if($_GET['id'] != $f3['player1cid'])
				{
					alert("You are already batteling someone.");
					redirect("?page=battle&id=".$f3['player1cid']);
				}
			}
		}
		

		if($f['level'] >= $f2['level'])
		{
			$leveldiff = $f['level']-$f2['level'];
		}
		else
		{
			$leveldiff = $f2['level']-$f['level'];
		}

		if($leveldiff > 3)
		{
			alert("You can't attack a player with a level difference more than 2 levels.");
			redirect("index.php");
		}
			
		if(isset($_SESSION['uid']))
		{
			echo '<img style="float:left;" src="img/characters/'.getCharPic($_SESSION['uid']).'" class="charpic width150">';

			echo '<table style="float:left;">';
			echo'
				<tr width="200"><td><b>HP</b><td>'.$f['hp'].'</td></tr>
				<tr width="200"><td><b>Energy</b><td>'.$f['energy'].'</td></tr>
				<tr width="200"><td><b>Attack</b><td>'.getCharTotalAttack($f['id']).'</td></tr>			
				<tr width="200"><td><b>Defence</b><td>'.getCharTotalDefence($f['id']).'</td></tr>';

			echo '</table>';
		}


		if(isset($_GET['id']))
		{
			

			echo '<img style="float:right;" src="img/characters/'.getCharPic(getAidFromCid($_GET['id'])).'" class="charpic width150">';
			echo '<table style="float:right;">';
			echo '
				<tr><td style="text-align:right;"><b>'.$f2['name'].'</b></td></tr>
				<tr><td width="200" style="text-align:right;"><b>'.getPollars($f2['aid']).'</b> Cash Pollars</td></tr>
				<tr><td style="text-align:right;">level <b>'.$f2['level'].'</b></td></tr>';

			echo '</table>';
			
		}

			

		if($_SERVER['REQUEST_METHOD'] == 'POST' && $_GET['page'] == 'battle' && isset($_GET['id']))
		{
			$cid = $_SESSION['cid'];
			$q = mysql_query("SELECT * FROM battle_log WHERE player1cid='$id' AND endtime > '$time' AND winner='0' OR player2cid ='$id' AND endtime > '$time' AND winner='0'");
			if(mysql_num_rows($q) == 0)
			{
				setBattle();
			}
		}
		else
		{
			$cid = $_SESSION['cid'];
			$q = mysql_query("SELECT * FROM battle_log WHERE player1cid='$cid' AND endtime > '$time' AND winner='0' OR player2cid ='$cid' AND endtime > '$time' AND winner='0'");
			if(mysql_num_rows($q) == 0)
			{
				echo '<form method="POST" action=""><button class="bsexy attackbtn">Attack '.$f2['name'].'</button></form>';
			}
			else
			{
				$f = mysql_fetch_array($q);
				echo '<div class="battlemessage">You are battling '.getNameFromCid($f['player2cid']).' in an intensive battle, there is <div id="starttime" style="display:none;">'.$f['endtime'].'</div><div id="timeleft"></div> of battle time left</div>';
			}
		}
	}




?>